package com.fitso.wicket;

import java.io.Serializable;

import org.apache.wicket.Request;
import org.apache.wicket.Session;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.fitso.model.bean.User;
import com.fitso.model.service.user.UserService;

/**
 * Fitso centric {@link WebSession}. Don't for the love load this this class up
 * with a bunch of SHIT! It is only for elements that MUST be in the session,
 * not for any base thing that you don't want to figure out how to do correctly.
 * 
 * @author Timothy Storm
 */
public class FitsoSession extends WebSession implements Serializable {
	// Only change on breaking changes, i.e., removing fields
	private static final long serialVersionUID = 1L;
	
	private User _user;

	@SpringBean(name = "UserService")
	private UserService _userService;

	public FitsoSession(Request request) {
		super(request);

		// wire spring dependencies
		InjectorHolder.getInjector().inject(this);
	}

	public void setUser(User user) {
		_user = user;
	}

	public User getUser() {
		return _user;
	}

	/**
	 * Determines if a user is signed in, e.g there is a user in the session
	 * 
	 * @return
	 */
	public boolean isSignedIn() {
		return _user != null;
	}

	/**
	 * Signs in a user given the email/password. If the signin is successful the
	 * user is added to the session.
	 * 
	 * @param email
	 * @param password
	 * @return true/false the sign in of the user was successful
	 */
	public boolean signIn(String email, String password) {
		return (_user = _userService.fetch(email, password)) != null;
	}

	public boolean signOut() {
		_user = null;
		invalidate();
		return true;
	}

	/**
	 * Returns back a Fitso centric session
	 * 
	 * @return
	 */
	public static FitsoSession get() {
		return (FitsoSession) Session.get();
	}
}
